import React, { useState, useEffect } from 'react'
import styles from './index.module.scss'
import { Flex, PickerView } from 'antd-mobile'
import classNames from 'classnames'
import { getHouseCondition } from '@/api/filter'
import { getCurrentCity } from '@/utils/city'
import FilterFooter from '../FilterFooter'
import { Spring, config } from 'react-spring/renderprops'

function Filter ({ onConditionChange }) {
  const [types] = useState([
    { name: '区域', type: 'area' },
    { name: '方式', type: 'mode' },
    { name: '租金', type: 'price' },
    { name: '筛选', type: 'more' }
  ])

  const [houseCondition, setHouseCondition] = useState(null)
  const [openType, setOpenType] = useState('')

  const [selectTitleValue, setSelectTitleValue] = useState({
    area: false,
    mode: false,
    price: false,
    more: false
  })

  const [selectValue, setSelectValue] = useState({
    area: ['area', 'null'],
    mode: ['null'],
    price: ['null'],
    more: []
  })

  const [pickerValues, setPickerValues] = useState({
    area: [],
    mode: [],
    price: []
  })

  const [moreValues, setMoreValues] = useState([])

  const getHouseConditionData = async () => {
    const { value } = await getCurrentCity()
    const res = await getHouseCondition(value)

    setHouseCondition(res.data.body)
  }

  useEffect(() => {
    getHouseConditionData()
  }, [])

  useEffect(() => {
    dealWithFilterTitleHighLight()
  }, [selectValue, openType])

  useEffect(() => {
    onConditionChange(selectValue)
  }, [selectValue])

  // 处理类型标题高亮
  const dealWithFilterTitleHighLight = () => {
    let tempObj = {}
    Object.keys(selectValue).forEach(type => {
      if (type === 'area') {
        tempObj[type] =
          selectValue.area.length > 1 && selectValue.area[1] !== 'null'
      } else if (type === 'mode') {
        tempObj[type] =
          selectValue.mode.length > 0 && selectValue.mode[0] !== 'null'
      } else if (type === 'price') {
        tempObj[type] =
          selectValue.price.length > 0 && selectValue.price[0] !== 'null'
      } else if (type === 'more') {
        tempObj[type] = selectValue.more.length > 0
      }
    })

    setSelectTitleValue(tempObj)
  }

  // 更改类型
  const changeType = type => {
    setOpenType(type)
    setSelectTitleValue({ ...selectTitleValue, [type]: true })
  }

  // 渲染标题
  const renderFilterTitle = () => {
    return (
      <Flex className={styles.filterTitle}>
        {types.map(item => {
          const isSelected = selectTitleValue[item.type]
          return (
            <Flex.Item key={item.type} onClick={() => changeType(item.type)}>
              <span
                className={classNames(styles.dropdown, {
                  [styles.selected]: isSelected
                })}
              >
                <span>{item.name}</span>
                <i className='iconfont icon-arrow' />
              </span>
            </Flex.Item>
          )
        })}
      </Flex>
    )
  }

  // 渲染遮罩
  const renderMask = () => {
    const isShow =
      openType === 'area' || openType === 'mode' || openType === 'price'

    // if (!isShow) return null

    // return <div onClick={() => setOpenType('')} className={styles.mask}></div>

    return (
      <Spring to={{ opacity: isShow ? 1 : 0 }} config={{ duration: 250 }}>
        {props => {
          if (props.opacity === 0) return null

          return (
            <div
              className={styles.mask}
              style={{ opacity: props.opacity }}
              onClick={() => setOpenType('')}
            ></div>
          )
        }}
      </Spring>
    )
  }

  // PickerView的值发生了改变
  const onChange = value => {
    setPickerValues({ ...pickerValues, [openType]: value })
  }

  // 渲染PickerView
  const renderFilterPickerView = () => {
    const { area, subway, rentType, price } = houseCondition
    const value = pickerValues[openType]

    let data = null
    let cols = 3

    switch (openType) {
      case 'area':
        cols = 3
        data = [area, subway]
        break

      case 'mode':
        cols = 1
        data = rentType
        break

      case 'price':
        cols = 1
        data = price

      default:
        break
    }

    return (
      <div>
        <PickerView onChange={onChange} value={value} data={data} cols={cols} />
        <FilterFooter
          onCancel={() => {
            setOpenType('')
          }}
          onOk={() => {
            setOpenType('')
            setSelectValue({ ...selectValue, ...pickerValues })
          }}
        />
      </div>
    )
  }

  const toggleSelect = value => {
    let oldValues = [...moreValues]

    if (oldValues.includes(value)) {
      oldValues = moreValues.filter(item => item !== value)
    } else {
      oldValues.push(value)
    }

    setMoreValues(oldValues)
  }

  const renderMoreItem = data => {
    return (
      <dd className={styles.dd}>
        {data.map(item => {
          return (
            <span
              onClick={() => toggleSelect(item.value)}
              key={item.value}
              className={classNames(styles.tag, {
                [styles.tagActive]: moreValues.includes(item.value)
              })}
            >
              {item.label}
            </span>
          )
        })}
      </dd>
    )
  }

  const renderMore = () => {
    const { roomType, oriented, floor, characteristic } = houseCondition
    return (
      <div className={styles.filterMore}>
        <div
          onClick={() => setOpenType('')}
          className={styles.filterMoreMask}
        ></div>
        <div className={styles.tags}>
          <dl className={styles.dl}>
            <dt className={styles.dt}>户型</dt>
            {renderMoreItem(roomType)}
            <dt className={styles.dt}>朝向</dt>
            {renderMoreItem(oriented)}
            <dt className={styles.dt}>楼层</dt>
            {renderMoreItem(floor)}
            <dt className={styles.dt}>房屋亮点</dt>
            {renderMoreItem(characteristic)}
          </dl>
        </div>
        <div className={styles.filterMoreFooter}>
          <FilterFooter
            cancelText='清除'
            onCancel={() => {
              setMoreValues([])
            }}
            onOk={() => {
              setOpenType('')
              setSelectValue({ ...selectValue, more: moreValues })
            }}
          />
        </div>
      </div>
    )
  }

  return (
    <div className={styles.root}>
      {renderMask()}
      <div className={styles.content}>
        {/* 渲染类型Title */}
        {renderFilterTitle()}
        {/* 渲染PickerView */}
        {houseCondition &&
          (openType === 'area' ||
            openType === 'mode' ||
            openType === 'price') &&
          renderFilterPickerView()}
        {/* 渲染more */}
        {houseCondition && openType === 'more' && renderMore()}
      </div>
    </div>
  )
}

export default Filter
